﻿using AuthorityCenter;
using LdtCommonLibraryHttp;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Data;
using System.Linq;
using System.Text;

namespace AuthorSync.Controllers
{
    /// <summary>
    /// 同步数据库授权法院操作
    /// </summary>
    [ApiController]
    [Route("[controller]")]
    public class SyncController : ControllerBase
    {
        private string judocSystem = "JUDGEDOCSYSTEM.";
        private readonly IHttpHelper httpHelper;
        private readonly ILogger<SyncController> logger;
        /// <summary>
        /// Initializes a new instance of the <see cref="SyncController"/> class.
        /// </summary>
        /// <param name="httpHelper">http</param>
        /// <param name="logger">The logger.</param>
        public SyncController(IHttpHelper httpHelper, ILogger<SyncController> logger)
        {
            this.httpHelper = httpHelper;
            this.logger = logger;
        }
        /// <summary>
        /// 同步
        /// </summary>
        /// <param name="obj">请求对象</param>
        /// <returns></returns>
        [HttpPost]
        [Route("sync")]
        public string Sync(PostSyscObj obj)
        {
            if (string.IsNullOrEmpty( obj.IP) && string.IsNullOrEmpty(obj.Port))
            {
                return "1";
            }
            if (!string.IsNullOrEmpty(obj.DataBaseType))
            {
                StringBuilder sqls = new StringBuilder();
                try
                {
                    SqlHelper sqlHelper = new SqlHelper("");
                    LdtJudge.DatabaseCore.Interfac.ISqlHelper helper = null;
                    switch (obj.DataBaseType)
                    {
                        case "sqlserver":
                            judocSystem = "Ldt_JudgeDocSystem.dbo.";
                            helper = LdtJudge.DatabaseHandle.Standard.DbHelperSQLFactory.CreateDatabaseHelper($"Data Source={obj.IP},{obj.Port};Initial Catalog=Ldt_JudgeDocSystem;User ID={obj.Username};Password={obj.Pwd}", LdtJudge.DatabaseCore.Common.DataBaseType.sqltype);
                            break;
                        case "dm"://达梦数据库
                            helper = LdtJudge.DatabaseHandle.Standard.DbHelperSQLFactory.CreateDatabaseHelper($"server={obj.IP}:{obj.Port};UID={obj.Username};PWD={obj.Pwd};encoding=GB18030;", LdtJudge.DatabaseCore.Common.DataBaseType.dmsqltype);
                            break;
                        case "mysql":
                            break;
                        default:
                            break;
                    }
                    if (helper != null)
                    {
                        if (obj.Isfirst)
                        {
                            string temp = $"update {judocSystem}SYS_Org_Court set OC_IsRightUse = 0";
                            sqls.AppendLine(temp);
                            helper.ExecuteNonQuery(temp);
                        }
                        foreach (var item in obj.Courts)
                        {
                            string temp00 = $" select CourtID,CH_Name,CH_Code,CH_ParentID,CH_LevelID from {judocSystem}SYS_Court_Prosecutor where CH_Code='{item}'";
                            sqls.AppendLine(temp00);
                            DataTable dt = helper.ExecuteReader(temp00);
                            if (dt != null && dt.Rows.Count > 0)
                            {
                                string courtID = dt.Rows[0]["CourtID"].ToString();
                                string cH_Name = dt.Rows[0]["CH_Name"].ToString();
                                string cH_Code = dt.Rows[0]["CH_Code"].ToString();
                                string cH_ParentID = dt.Rows[0]["CH_ParentID"].ToString();
                                string cH_LevelID = dt.Rows[0]["CH_LevelID"].ToString();
                                string temp11 = $"select OC_ID from {judocSystem}SYS_Org_Court where OC_ID='{courtID}' and OC_Name='{cH_Name}' and OC_Code='{cH_Code}'and OC_ParentID='{cH_ParentID}'";
                                sqls.AppendLine(temp11);
                                bool exitsID = null == helper.ExecuteScalar(temp11);
                                if (exitsID)
                                {
                                    temp11 = $"insert into {judocSystem}SYS_Org_Court (OC_ID, OC_Name, OC_Code, OC_ShowIndex, OC_Level, OC_IsRightUse, OC_ParentID) values ('{courtID}','{cH_Name}','{cH_Code}','1','{cH_LevelID}','1','{cH_ParentID}')";
                                }
                                else
                                {
                                    temp11 = $"update {judocSystem}SYS_Org_Court set OC_IsRightUse = 1 where OC_Code='{cH_Code}'";
                                }
                                helper.ExecuteNonQuery(temp11);
                                sqls.AppendLine(temp11);
                                string departmentId = sqlHelper.CreateKeyID();

                                string temp3 = $"select ID from {judocSystem}SYS_Org_Department where Name='信息科' and CourtId='{courtID}'";
                                sqls.AppendLine(temp3);
                                exitsID = null == helper.ExecuteScalar(temp3);
                                if (exitsID)
                                {
                                    string temp2 = $"insert into {judocSystem}SYS_Org_Department (ID, Name, CourtId, Jgbs, OutRelatID) values('{departmentId}', '信息科', '{courtID}', '1000', '99999999')";
                                    sqls.AppendLine(temp2);
                                    helper.ExecuteNonQuery(temp2);
                                }
                                string orgId = sqlHelper.CreateKeyID();
                                string temp1 = $"select ID from {judocSystem}SYS_Org_User where UserName='ldtadmin' and CnName='管理员'and CourtId='{courtID}'";
                                sqls.AppendLine(temp1);
                                exitsID = null == helper.ExecuteScalar(temp1);
                                if (exitsID)
                                {
                                    string temp0 = $"insert into {judocSystem}SYS_Org_User (ID, UserName, CnName, Password, CourtId, DepartmentId, Jgbs, OutRelateID) values('{orgId}', 'ldtadmin', '管理员', 'ldt123', '{courtID}', '{departmentId}', '1000', '99999999')";
                                    sqls.AppendLine(temp0);
                                    helper.ExecuteNonQuery(temp0);
                                }
                            }
                        }
                        System.IO.File.WriteAllText(AppContext.BaseDirectory + "/同步法院和帐号.txt", sqls.ToString());
                    }
                    else
                    {
                        System.IO.File.WriteAllText(AppContext.BaseDirectory + "/error.txt", "未成功创建数据库连接" + JsonConvert.SerializeObject(obj));
                        return "0";
                    }
                }
                catch (Exception e1)
                {
                    Console.WriteLine(e1.Message);
                    System.IO.File.WriteAllText(AppContext.BaseDirectory + "/error.txt", e1.Message + e1.StackTrace + sqls.ToString());
                    return "0";
                }
            }
            else
            {
                try
                {
                    System.IO.File.AppendAllText(AppContext.BaseDirectory + "/info.txt", JsonConvert.SerializeObject(obj));
                    string basePath;
                    if (AuthorQTService.IsLinux())
                    {
                        basePath = "/usr/etc";
                    }
                    else
                    {
                        basePath = "c:/Windows";
                    }
                    var departStrs = System.IO.File.ReadAllLines(basePath + @"/ldt/courtmess");
                    var departObjs = departStrs.Select(p =>
                    {
                        var t = p.Split(",");
                        return new { deptId = t[0], parentId = t[1], standardCode = t[2], deptName = t[3], representativeWord = t[4], courtId = t.Length > 5 ? t[5] : "", deptType = t.Length > 6 ? t[6] : "", status = 0, authCourtFlag = 1 };
                    });
                    var str = JsonConvert.SerializeObject(departObjs.Where(p => obj.Courts.Contains(p.deptId)));
                    System.IO.File.AppendAllText(AppContext.BaseDirectory + "/info.txt", str);
                    var result = httpHelper.PostAsync($"http://{obj.IP}:{obj.Port}/api/v1/authCourt", str);
                    System.IO.File.AppendAllText(AppContext.BaseDirectory + "/info.txt", "\r\n" + result.Result.Content.ReadAsStringAsync().Result);
                    if (result.Result.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        var obj1 = JsonConvert.DeserializeObject<dynamic>(result.Result.Content.ReadAsStringAsync().Result);
                        if (obj1.code.Value != 0)
                        {
                            throw new Exception("访问用户中心错误：" + obj1.msg);
                        }
                    }
                    else
                    {
                        throw new Exception("访问用户中心错误：" + result.Result.Content.ReadAsStringAsync().Result);
                    }
                }
                catch (Exception e1)
                {
                    logger.LogError("", e1);
                    System.IO.File.WriteAllText(AppContext.BaseDirectory + "/error.txt", e1.Message + e1.StackTrace);
                    return "0";
                }
            }
            return "1";
        }

        /// <summary>
        /// 数据库连接
        /// </summary>
        /// <param name="obj">请求对象</param>
        /// <returns></returns>
        [HttpPost]
        [Route("Connect")]
        public string Connect(PostSyscObj obj)
        {
            if (!string.IsNullOrEmpty(obj.DataBaseType))
            {
                try
                {
                    LdtJudge.DatabaseCore.Interfac.ISqlHelper helper;
                    switch (obj.DataBaseType)
                    {
                        case "sqlserver":
                            helper = LdtJudge.DatabaseHandle.Standard.DbHelperSQLFactory.CreateDatabaseHelper($"Data Source={obj.IP},{obj.Port};Initial Catalog=Ldt_JudgeDocSystem;User ID={obj.Username};Password={obj.Pwd}", LdtJudge.DatabaseCore.Common.DataBaseType.sqltype);
                            helper.ExecuteScalar("select @@VERSION");
                            break;
                        case "dm"://达梦数据库
                            helper = LdtJudge.DatabaseHandle.Standard.DbHelperSQLFactory.CreateDatabaseHelper($"server={obj.IP}:{obj.Port};UID={obj.Username};PWD={obj.Pwd};encoding=GB18030;", LdtJudge.DatabaseCore.Common.DataBaseType.dmsqltype);
                            helper.ExecuteScalar("SELECT top 1 * FROM V$VERSION");
                            break;
                        default:
                            break;
                    }
                    return "1";
                }
                catch (Exception e1)
                {
                    Console.WriteLine(e1.Message);
                    return "0";
                }
            }
            else
            {
                try
                {
                    httpHelper.Get($"http://{obj.IP}:{obj.Port}");
                    return "1";
                }
                catch (Exception e1)
                {
                    logger.LogError("", e1);
                    return "0";
                }
            }
        }
    }
}
